
/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.gtask.remote;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;


public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {

    private final int mNotificationId = 5234235;  // 改为 final 实例变量
    public interface OnCompleteListener {
        void onComplete();
    }

    private Context mContext;

    private NotificationManager mNotifiManager;

    private GTaskManager mTaskManager;

    private OnCompleteListener mOnCompleteListener;

    public GTaskASyncTask(Context context, OnCompleteListener listener) {
        mContext = context;
        mOnCompleteListener = listener;
        mNotifiManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mTaskManager = GTaskManager.getInstance();
    }

    public void cancelSync() {
        mTaskManager.cancelSync();
    }

    public void publishProgess(String message) {
        publishProgress(new String[] {
            message
        });
    }

    private void showNotification(int tickerId, String content) {
        // 声明一个 PendingIntent 对象
        PendingIntent pendingIntent;

        // 判断 tickerId 是否为成功标识
        if (tickerId != R.string.ticker_success) {
            // 如果 tickerId 不等于成功标识，则启动 NotesPreferenceActivity
            pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
                    NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE);
        } else {
            // 如果 tickerId 等于成功标识，则启动 NotesListActivity
            pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
                    NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE);
        }

        // 创建通知构建器 Notification.Builder
        Notification.Builder builder = new Notification.Builder(mContext)
                .setAutoCancel(true)  // 当用户点击通知时，自动取消该通知
                .setContentTitle(mContext.getString(R.string.app_name))  // 设置通知的标题为应用的名称
                .setContentText(content)  // 设置通知的文本内容为传入的内容
                .setContentIntent(pendingIntent)  // 设置通知点击时要执行的 PendingIntent（打开指定的 Activity）
                .setWhen(System.currentTimeMillis())  // 设置通知的时间戳为当前系统时间
                .setOngoing(true);  // 设置通知为 "正在进行中"（不能滑动移除）

        // 通过构建器创建通知对象
        Notification notification = builder.getNotification();

        // 使用通知管理器显示通知，GTASK_SYNC_NOTIFICATION_ID 为通知的唯一 ID
        mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
    }


    @Override
    protected Integer doInBackground(Void... unused) {
        publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
                .getSyncAccountName(mContext)));
        return mTaskManager.sync(mContext, this);
    }

    @Override
    protected void onProgressUpdate(String... progress) {
        showNotification(R.string.ticker_syncing, progress[0]);
        if (mContext instanceof GTaskSyncService) {
            ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
        }
    }

    @Override
    protected void onPostExecute(Integer result) {
        // 根据任务执行的结果，显示不同的通知和处理逻辑

        // 如果 result 表示同步成功
        if (result == GTaskManager.STATE_SUCCESS) {
            // 显示同步成功的通知，通知内容包括同步的账户名
            showNotification(R.string.ticker_success, mContext.getString(
                    R.string.success_sync_account, mTaskManager.getSyncAccount()));

            // 更新最后同步时间到当前时间
            NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());

            // 如果 result 表示网络错误
        } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
            // 显示网络错误的通知
            showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));

            // 如果 result 表示内部错误
        } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
            // 显示内部错误的通知
            showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));

            // 如果 result 表示同步被取消
        } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
            // 显示同步被取消的通知
            showNotification(R.string.ticker_cancel, mContext
                    .getString(R.string.error_sync_cancelled));
        }

        // 如果任务完成后设置了监听器（mOnCompleteListener），则执行监听器的回调方法
        if (mOnCompleteListener != null) {
            // 在新的线程中执行监听器的 onComplete 方法，避免阻塞主线程
            new Thread(new Runnable() {
                public void run() {
                    // 调用 onComplete 方法通知任务完成
                    mOnCompleteListener.onComplete();
                }
            }).start();
        }
    }

}
